﻿var ApptexCommon = (ApptexCommon || {});
var ApptexTemplatesMapping = (ApptexTemplatesMapping || {});
var ApptexLoadedJSFiles = (ApptexLoadedJSFiles || {});

(function () {

    ApptexCommon.GetView = function (precompileTemplate, ctx, fields) {
        registerAllHelpers();
        ctx = getfieldsmappingCtx(ctx, fields);
        ctx.viewNoBraces = (ctx.ListSchema.View.replace("{", "")).replace("}", "");

        var html = precompileTemplate(ctx);;
        html = "".concat("<table id='", ctx.listName, "-", ctx.view, "' view='", ctx.viewNoBraces, "' class='ms-listviewtable' style='width: 100%' cellspacing='0' cellpadding='0' border='0'><tr><td>", html, "</td></tr></table>");

        return html;
    }

    var getfieldsmappingCtx = function (ctx, fields) {
        for (var i = 0; i < ctx.ListData.Row.length; i++) {

            ctx.ListData.Row[i].MapFields = {};

            for (var propertyName in fields) {
                ctx.ListData.Row[i].MapFields[propertyName] = ctx.ListData.Row[i][fields[propertyName]];
            }
        }

        return ctx;
    };

    var registerAllHelpers = function () {

        if (!ApptexCommon.isHelpersRegistered) {
            Handlebars.registerHelper('GetFirstImageSrc', function (options) {

                var content = $('<div/>').html(options.fn(this)).text()
                var regex = /<img.*?src='(.*?)'/;
                var src = regex.exec(content);

                if (!src) {
                    regex = /<img.*?src="(.*?)"/;
                    src = regex.exec(content);
                }

                if (src && src[1]) {
                    return src[1];
                }
                else {
                    return null;
                }
            });

            Handlebars.registerHelper('GetFirstImageSrcWithoutQuery', function (options) {

                var content = $('<div/>').html(options.fn(this)).text()
                var regex = /<img.*?src='(.*?)'/;
                var src = regex.exec(content);

                if (!src) {
                    regex = /<img.*?src="(.*?)"/;
                    src = regex.exec(content);
                }

                if (src && src[1]) {
                    if (src[1].indexOf("?")) {
                        return src[1].split("?")[0];
                    } else {
                        return src[1];
                    }
                }
                else {
                    return null;
                }
            });

            Handlebars.registerHelper('GetDefaultIfEmpty', function (defaultValue, options) {
                var val = options.fn(this) ? options.fn(this) : defaultValue;
                return val;
            });

            Handlebars.registerHelper('GetRelativeDateTimeString', function (options) {
                return GetRelativeDateTimeString(options.fn(this));
            });

            Handlebars.registerHelper('GetValueIfObjectWithinArray', function (array, propName, propValue, rtnIfValue, rtnIfNotValue, options) {

                if (propValue && array) {
                    var existArr = jQuery.grep(array, function (e) {
                        return e[propName].toString().toLowerCase() == propValue.toString().toLowerCase();
                    });

                    if (existArr.length > 0) {
                        return rtnIfValue;
                    }
                    else {
                        return rtnIfNotValue;
                    }
                } else {
                    return rtnIfNotValue;
                }

                return rtnIfNotValue;
            });

            Handlebars.registerHelper('GetValueIfEquals', function (value1, value2, rtnIfValue, rtnIfNotValue, options) {
                if (value1 === value2) {
                    return rtnIfValue;
                }

                return rtnIfNotValue;
            });

            Handlebars.registerHelper('IfEquals', function (value1, value2, options) {
                if (value1 === value2) {
                    return options.fn(this);
                }
                return options.inverse(this);
            });

            Handlebars.registerHelper('UnlessEquals', function (value1, value2, options) {

                if (value1 !== value2) {
                    return options.fn(this);
                }
                return null;
            });

            Handlebars.registerHelper('IfHasPermission', function (permission, options) {
                var retuernResult = SP.ScriptHelpers.hasPermission(SP.ScriptHelpers.getListLevelPermissionMask(this), SP.ListLevelPermissionMask[permission]);

                if (retuernResult) {
                    return options.fn(this);
                }
                return options.inverse(this);
            });

            Handlebars.registerHelper('UnlessHasPermission', function (permission, options) {
                var retuernResult = SP.ScriptHelpers.hasPermission(SP.ScriptHelpers.getListLevelPermissionMask(this), SP.ListLevelPermissionMask[permission]);

                if (!retuernResult) {
                    return options.fn(this);
                }
                return null;
            });

            Handlebars.registerHelper('IfObjectWithinArray', function (array, propName, propValue, options) {

                if (propValue && array) {
                    var existArr = jQuery.grep(array, function (e) {
                        return e[propName].toString().toLowerCase() == propValue.toString().toLowerCase();
                    });

                    if (existArr.length > 0) {
                        return options.fn(this);
                    }
                }

                return options.inverse(this);
            });

            Handlebars.registerHelper('UnlessObjectWithinArray', function (array, propName, propValue, options) {

                if (propValue && array) {
                    var existArr = jQuery.grep(array, function (e) {
                        return e[propName].toString().toLowerCase() == propValue.toString().toLowerCase();
                    });

                    if (existArr.length == 0) {
                        return options.fn(this);
                    }
                }

                return null;
            });

            Handlebars.registerHelper('IfFirstImageSrcExist', function (content, options) {

                var regex = /<img.*?src='(.*?)'/;
                var src = regex.exec(content);

                if (!src) {
                    regex = /<img.*?src="(.*?)"/;
                    src = regex.exec(content);
                }

                if (src && src[1]) {
                    return options.fn(this)
                }

            });

            ApptexCommon.isHelpersRegistered = true;
        }
    };
}());

var RenderListView = (function (renderCtx, wpq, templateBody, bAnimation, bRenderHiddenFooter) {
    var original_RenderListView = RenderListView;

    return function (renderCtx, wpq, templateBody, bAnimation, bRenderHiddenFooter) {

        var tempBaseViewID = renderCtx.BaseViewID;

        if (ApptexTemplatesMapping[renderCtx.listName.toLowerCase()]) {
            renderCtx.BaseViewID = ApptexTemplatesMapping[renderCtx.listName.toLowerCase()];
        }

        original_RenderListView(renderCtx, wpq, templateBody, bAnimation, bRenderHiddenFooter);
        renderCtx.BaseViewID = tempBaseViewID;
    }
})();
